package com.weir.quarkus.base.system.utils;

import lombok.extern.slf4j.Slf4j;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.*;
import jakarta.ws.rs.BadRequestException;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.weir.quarkus.base.system.vo.VuePageListVo;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 动态查询封装
 *
 * @author yujianyou
 * @date 2021/12/6 9:17
 * @email 597907730@qq.com
 */
@Slf4j
@ApplicationScoped
@SuppressWarnings({ "unchecked", "rawtypes" })
public class QueryHelper {

	/**
	 * 动态组装查询条件
	 * @param <R>
	 * @param <Q>
	 * @param root
	 * @param query
	 * @param cb
	 * @return
	 */
	public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {

        List<Predicate> list = new ArrayList<>();
        if (query == null) {
            return cb.and(list.toArray(new Predicate[0]));
        }
        try {
            List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
            for (Field field : fields) {
                boolean accessible = field.isAccessible();
                // 设置对象的访问权限，保证对private的属性的访
                field.setAccessible(true);
                // 属性是否存在查询注解
                Query q = field.getAnnotation(Query.class);
                if (q != null) {
                    String propName = q.propName();
                    String joinName = q.joinName(); //  关联查询
                    String blurry = q.blurry(); // 多字段模糊查询
                    String attributeName = isBlank(propName) ? field.getName() : propName;
                    Class<?> fieldType = field.getType();
                    Object val = field.get(query); // 属性是否有值
                    if (null == val || val.equals(null)) {
                        continue;
                    }
                    // 多字段模糊查询  eg: (xx like '%v%' or xxx like '%v%' or xxxx like '%v%')
                    if (StringUtils.isNotBlank(blurry)) {
                        String[] blurrys = blurry.split(",");
                        List<Predicate> orPredicate = new ArrayList<>();
                        for (String s : blurrys) {
                            orPredicate.add(cb.like(root.get(s)
                                    .as(String.class), "%" + val.toString() + "%"));
                        }
                        Predicate[] p = new Predicate[orPredicate.size()];
                        list.add(cb.or(orPredicate.toArray(p)));
                        continue;
                    }
                    // 关联查询 eg: (join xx on )
                    Join join = null;
                    if (StringUtils.isNotBlank(joinName)) {
                        String[] joinNames = joinName.split(">");
                        for (String name : joinNames) {
                            switch (q.join()) {
                                case LEFT:
                                    if (isNotNull(join) && isNotNull(val)) {
                                        join = join.join(name, JoinType.LEFT);
                                    } else {
                                        join = root.join(name, JoinType.LEFT);
                                    }
                                    break;
                                case RIGHT:
                                    if (isNotNull(join) && isNotNull(val)) {
                                        join = join.join(name, JoinType.RIGHT);
                                    } else {
                                        join = root.join(name, JoinType.RIGHT);
                                    }
                                    break;
                                case INNER:
                                    if (isNotNull(join) && isNotNull(val)) {
                                        join = join.join(name, JoinType.INNER);
                                    } else {
                                        join = root.join(name, JoinType.INNER);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    switch (q.type()) {
                        case EQUAL: // 等于
                            list.add(cb.equal(getExpression(attributeName, join, root)
                                    .as((Class<? extends Comparable>) fieldType), val));
                            break;
                        case GREATER_THAN: //   大于等于
                            list.add(cb.greaterThanOrEqualTo(getExpression(attributeName, join, root)
                                    .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                            break;
                        case GREATER:  //   大于
                            list.add(cb.greaterThan(getExpression(attributeName, join, root)
                                    .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                            break;
                        case LESS_THAN:  //   小于等于
                            list.add(cb.lessThanOrEqualTo(getExpression(attributeName, join, root)
                                    .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                            break;
                        case LESS_THAN_NQ:  //  小于
                            list.add(cb.lessThan(getExpression(attributeName, join, root)
                                    .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                            break;
                        case INNER_LIKE:  //   全模糊查询
                            list.add(cb.like(getExpression(attributeName, join, root)
                                    .as(String.class), "%" + val.toString() + "%"));
                            break;
                        case LEFT_LIKE:  //   左模糊查询
                            list.add(cb.like(getExpression(attributeName, join, root)
                                    .as(String.class), "%" + val.toString()));
                            break;
                        case RIGHT_LIKE:  //  右模糊查询
                            list.add(cb.like(getExpression(attributeName, join, root)
                                    .as(String.class), val.toString() + "%"));
                            break;
                        case IN: // 包含in (1,2,3)
                            if (CollectionUtils.isNotEmpty((Collection<Object>) val)) {
                                list.add(getExpression(attributeName, join, root).in((Collection<Object>) val));
                            }
                            break;
                        case NOT_IN:  // 不包含 not in (1,2,3)
                            if (CollectionUtils.isNotEmpty((Collection<Object>) val)) {
                                list.add(getExpression(attributeName, join, root).in((Collection<Object>) val).not());
                            }
                            break;
                        case NOT_EQUAL:  // 不等于
                            list.add(cb.notEqual(getExpression(attributeName, join, root), val));
                            break;
                        case NOT_NULL:  // 不为空
                            list.add(cb.isNotNull(getExpression(attributeName, join, root)));
                            break;
                        case IS_NULL:  // 为空
                            list.add(cb.isNull(getExpression(attributeName, join, root)));
                            break;
                        case BETWEEN:
                            if (CollectionUtils.isNotEmpty((Collection<Object>) val)) {
                                List<Object> between = new ArrayList<>((List<Object>) val);
                                list.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()),
                                        (Comparable) between.get(0), (Comparable) between.get(1)));
                            }

                            break;
                        default:
                            break;
                    }
                }
                field.setAccessible(accessible);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        int size = list.size();
        return cb.and(list.toArray(new Predicate[size]));
    }
	
	public static boolean isNotNull(Object obj) {
		return null != obj && false == obj.equals(null);
	}

    private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {
        if (isNotNull(join)) {
            return join.get(attributeName);
        } else {
            return root.get(attributeName);
        }
    }

    public static <T> List<Order> getOrder(CriteriaBuilder cb, Root<T> root, List<String> sort) {
        List<Order> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sort)) {
            sort.forEach(e -> {
                String[] strArray = e.split(",");
                if ("desc".equalsIgnoreCase(strArray[1])) {
                    list.add(cb.desc(root.get(strArray[0])));
                } else {
                    list.add(cb.asc(root.get(strArray[0])));
                }
            });
        }
        return list;
    }

    public static <T, Q> TypedQuery<T> createQueryReturn(EntityManager entityManager, Class<T> tClass, Q query) {
        try {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<T> criteriaQuery = cb.createQuery(tClass);
            Root<T> root = criteriaQuery.from(tClass);
            // 获取处理后的查询参数
            Predicate predicate = QueryHelper.getPredicate(root, query, cb);
            // 添加到where后面
            criteriaQuery.where(predicate);
            // 排序字段不为空时，添加排序参数
            List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
            List<String> sortList = null;
            for (Field field : fields) {
                boolean accessible = field.isAccessible();
                // 设置对象的访问权限，保证对private的属性的访
                field.setAccessible(true);
                if ("sort".equalsIgnoreCase(field.getName())) {
                    sortList = (List<String>) field.get(query);
                }

                field.setAccessible(accessible);
            }

            if (CollectionUtils.isNotEmpty(sortList)) {
                criteriaQuery.orderBy(getOrder(cb, root, sortList));
            }

            return entityManager.createQuery(criteriaQuery);
        } catch (Exception e) {
            log.error("构建查询异常：" + e.getMessage());
            throw new BadRequestException(e.getMessage());
        }
    }
    /**
     * 分页查询
     * @param <T>
     * @param <Q>
     * @param entityManager
     * @param tClass
     * @param query
     * @return
     */
    public static <T, Q> VuePageListVo<T> createQueryPage(EntityManager entityManager, Class<T> tClass, Q query) {
        try {
            int page = 0;
            int size = 10;
            // CriteriaBuilder是一个工厂类，用来创建安全查询的criteriaQuery对象。该对象是用来构建查询的。
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            // 构建查询，必须指定实体类(jpa 实体)
            CriteriaQuery<T> criteriaQuery = cb.createQuery(tClass);
            
            Root<T> root = criteriaQuery.from(tClass);
            // 获取处理后的查询参数
            Predicate predicate = getPredicate(root, query, cb);
            // 添加到where后面
            criteriaQuery.where(predicate);
            // 排序字段不为空时，添加排序参数
            List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
            List<String> sortList = null;
            for (Field field : fields) {
                boolean accessible = field.isAccessible();
                // 设置对象的访问权限，保证对private的属性的访
                field.setAccessible(true);
                if ("sort".equalsIgnoreCase(field.getName())) {
                    sortList = (List<String>) field.get(query);
                }
                if ("page".equalsIgnoreCase(field.getName())) {
                    page = (Integer) field.get(query) - 1;
                }
                if ("pageSize".equalsIgnoreCase(field.getName())) {
                    size = (Integer) field.get(query);
                }

                field.setAccessible(accessible);
            }

            if (CollectionUtils.isNotEmpty(sortList)) {
                criteriaQuery.orderBy(getOrder(cb, root, sortList));
            }
            TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery);
            VuePageListVo<T> pageForTypedQuery = VuePageUtil.toPageForTypedQuery(typedQuery, new VuePageListVo<>(), page, size);
            
//            result.put("total", typedQuery.getResultList().size());
//            result.put("data", typedQuery.setFirstResult(page * size).setMaxResults(size).getResultList());

            return pageForTypedQuery;
        } catch (Exception e) {
            log.error("构建查询异常：" + e.getMessage());
            throw new BadRequestException(e.getMessage());
        }
    }


    private static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    /**
     * 获取对象每个属性
     * @param clazz
     * @param fields
     * @return
     */
    public static List<Field> getAllFields(Class clazz, List<Field> fields) {
        if (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            getAllFields(clazz.getSuperclass(), fields);
        }
        return fields;
    }
}
